package com.ruoyi.util;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import lombok.extern.slf4j.Slf4j;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

/**
 * TODO
 *
 * @author chenchuan2
 * @date 2024-04-05 22:26:47
 */
@Slf4j
public class GshQrcodeUtil {

    private static final String imagePath = "/root/store/background.jpg";
    private static final int qrWidth = 700;
    private static final int qrHeight = 700;
    private static final int qrX = 290;
    private static final int qrY = 1010;


    /**
     * @param text
     * @return 生成二维码地址
     */
    public static String generateQRCodeWithImage(String text) {
        try {
            // Generate QR Code
            BitMatrix bitMatrix = new MultiFormatWriter().encode(text, BarcodeFormat.QR_CODE, qrWidth, qrHeight);

            // Convert BitMatrix to BufferedImage
            BufferedImage qrImage = MatrixToImageWriter.toBufferedImage(bitMatrix);

            // Load background image
            BufferedImage backgroundImage = ImageIO.read(new File(imagePath));

            // Create new BufferedImage with the same size as the background image
            BufferedImage combined = new BufferedImage(backgroundImage.getWidth(), backgroundImage.getHeight(), BufferedImage.TYPE_INT_ARGB);

            // Draw the background image onto the new image
            Graphics2D graphics = combined.createGraphics();
            graphics.drawImage(backgroundImage, 0, 0, null);

            // Calculate the position to place the QR Code
            int qrX = 290;
            int qrY = 1010;

            // Draw QR Code onto the new image
            graphics.drawImage(qrImage, qrX, qrY, null);

            // Dispose the graphics
            graphics.dispose();

            String filePath = "/root/store/" + text + ".png";
            // Save the combined image with QR Code
            File outputFile = new File(filePath);
            ImageIO.write(combined, "PNG", outputFile);
            return filePath;
        } catch (IOException | WriterException e) {
            log.error("generateQRCodeWithImage fail", e);
            throw new IllegalArgumentException("generateQRCodeWithImage fail");
        }
    }
}
